<?php


namespace App\Services;


use Illuminate\Foundation\Application;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger as LoggerFile;

/**
 * @method static void info($msg, array $context = [], $type = 'info')
 */
class Logger
{
    /**
     * @var Logger
     */
    private static $monolog;

    public static function getMonolog()
    {
        return new LoggerFile(self::channel());
    }

    public static function __callStatic($name, $arguments)
    {
        static::write($arguments[0], isset($arguments[2]) ? $arguments[2] : 'info', $name, isset($arguments[1]) ? $arguments[1] : []);
    }

    protected static function write($msg, $type, $category, $context = [])
    {
        $file = static::getCommonLogDir($category);
        $monolog = self::getMonolog();
        $monolog->pushHandler(new RotatingFileHandler($file));

        // 将类别记录到日志中
        $monolog->pushProcessor(function ($record)use ($category){
            $record['level_name'] = "{$record['level_name']}.[{$category}]";
            return $record;
        });

        $monolog->$type($msg, [$context]);
    }

    /**
     * 获取日志存储路径
     * @param $category
     * @param bool $noDate
     * @return string
     */
    public static function getCommonLogDir($category, $noDate = false)
    {
        $log = storage_path('logs' . DIRECTORY_SEPARATOR . $category . DIRECTORY_SEPARATOR . $category . '.log');
        if (!$noDate) {
            $date = date('Ymd');
            $log = storage_path('logs' . DIRECTORY_SEPARATOR . $category . DIRECTORY_SEPARATOR . $category . $date . '.log');
        }
        return $log;
    }

    protected static function channel()
    {
        /** @var Application $app */
        $app = app();
        if ($app->bound('config') &&
            $channel = $app->make('config')->get('app.log_channel')) {
            return $channel;
        }

        return $app->bound('env') ? $app->environment() : 'production';
    }

}
